package cqrtplm.listener;

import cn.hutool.extra.spring.SpringUtil;
import com.hustcad.plm.pdm.workflow.annotion.CustomListener;
import com.hustcad.plm.pdm.workflow.model.constant.ProcessConstant;
import com.ty.basic.entity.org.UserDO;
import com.ty.basic.session.TyAccountContext;
import cqrtplm.service.FlowControlService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.flowable.engine.delegate.ExecutionListener;

import java.math.BigInteger;

@Slf4j
@CustomListener(category = "润通", description = "设置发起者部门流程监听")
public class DepartmentSupervisorListener implements ExecutionListener {

    @Override
    public void notify(DelegateExecution execution) {

        String workFlowContainerId = execution.getProcessInstanceBusinessKey();
        log.info("----------润通----设置发起者部门流程监听------开始------workFlowContainerId:{}----->>>", workFlowContainerId);

        if (StringUtils.isBlank(workFlowContainerId)) {
            workFlowContainerId = execution.getVariable(ProcessConstant.WORK_FLOW_CONTAINER_ID).toString();
        }

        try {
            UserDO initiator = TyAccountContext.getUser();
            if (initiator == null) {
                log.warn("无法获取发起者信息，跳过角色分支判断");
                return;
            }
            String finalWorkFlowContainerId = workFlowContainerId;
            FlowControlService flowControlService = SpringUtil.getBean(FlowControlService.class);

            flowControlService.checkDepartmentSupervisor(
                    new BigInteger(finalWorkFlowContainerId),
                    initiator,
                    execution
            );

        }catch (Exception e) {
            log.error("设置发起者部门流程监听失败", e);
            throw new RuntimeException("设置发起者部门流程监听失败", e);
        }
    }
}
